package com.zl.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zl.common.Result;
import com.zl.dto.UserDto;
import com.zl.entity.UserEntity;
import com.zl.mapper.UserMapper;
import com.zl.service.IUserService;
//import com.jiahao.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class IUserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public UserEntity getById(int id) {
        return getById(id);
    }

    @Override
    public Result login(UserDto userDto) {
        //判断username是否为空值
        String username=userDto.getUsername();
        if(username==null){
            //如果username为空  返回错误信息
            return Result.fail("您的用户名为空！");
        }
        UserEntity userEntity = userMapper.getByUserName(username);
//        UserEntity userEntity = userMapper.selectOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getUsername,username));
        if(userEntity==null){
            //如果查询数据为空   返回错误信息
            return Result.fail("未查询到该用户");
        }

        //进行密码比对
        if(!userDto.getPassword().equals(userEntity.getPassword())){
            //密码错误
            return Result.fail("密码错误");
        }

        //成功
        return Result.ok("登录成功");
    }

    @Override
    @Transactional
    public Result register(UserDto userDto) {
        //判断username是否为空值
        String username=userDto.getUsername();
        String pwd=userDto.getPassword();
        if(username==null||pwd==null){
            //如果username为空  返回错误信息
            return Result.fail("您的用户名或密码为空！");
        }
        //根据username查询用户信息
        Long count = lambdaQuery()
                .eq(UserEntity::getUsername, username).count();
        if(count!=0){
            return Result.fail("该用户已存在，请直接登录");
        }

        //用户不存在，保存
        UserEntity newUser = new UserEntity();
        BeanUtils.copyProperties(userDto,newUser);
        save(newUser);
        return Result.ok("注册成功");
    }


}
